package com.malex.mxtracker.servlet;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.malex.mxtracker.action.ActionHandler;
import com.malex.mxtracker.action.ActionResult;
import com.malex.mxtracker.exception.WrongCommandException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Manusovich Alexander
 */
@SuppressWarnings("serial")
public class XMPPReceiverServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        XMPPService xmpp = XMPPServiceFactory.getXMPPService();
        Message message = xmpp.parseMessage(req);

        JID fromJid = message.getFromJid();
        String body = message.getBody();

        try {
            ActionResult result = new ActionHandler(body, fromJid.getId()).execute();
            StringBuffer sb = new StringBuffer();
            if (result != null && result.getReport() != null) {
                for (String s : result.getReport()) {
                    sb.append(s).append("\n");
                }
                anwser(xmpp, fromJid, sb.toString());
            }
        } catch (WrongCommandException e) {
            e.printStackTrace();
            anwser(xmpp, fromJid, e.getMessage());
        }
    }

    private void anwser(final XMPPService xmpp, final JID fromJid, final String body) {
        Message msg = new MessageBuilder()
                .withRecipientJids(fromJid)
                .withBody(body)
                .build();
        if (xmpp.getPresence(fromJid).isAvailable()) {
            xmpp.sendMessage(msg);
        }
    }
}